<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\user_center\logic\user;
use think\facade\Hook;
use think\DB;
use think\facade\Cache;
class Balancelogic{

	/**
     * 储值订单创建
     * @param  int $uid  			用户ID
     * @param  int $price    	储值金额
     * @author Nuruto丶宝石
     * @return array_out
     */
    public function order_create($uid, $price){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'uid'		 	=> $uid,
                'price'   	    => $price,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            
            //生成订单
            $ordercode = date('YmdHis', time()).rand(100000,999999);
            $uid = $uid;
            $pay_type = 0;
            $pay_price = $price;
            //$pay_price = 0.01;//临时
            $rel3 = model('UcMemberBalance', 'model\user') -> addData($uid, $ordercode, $pay_price, $pay_type = 0, $pay_status = 0);
            if($rel3['code'] != 200) array_out(-1003, '订单生成失败');//后置错误 -1003
			$rel_list['orderId'] = $rel3['data'];
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/
			DB::commit();
			return array_out(200, 'success', $rel_list);
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    	
    }

    /**
     * 订单支付
     * @param  int $uid  			用户ID
     * @param  int $order_id    	订单id
     * @param  int $pay_type    	支付类型
     * @author Nuruto丶宝石
     * @return array_out
     */
    public function order_pay($uid, $order_id, $pay_type){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'uid'		 	    => $uid,
                'order_id'   	    => $order_id,
                'pay_type'   	    => $pay_type,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            
            switch ($pay_type) {
				case 1://微信支付
					$rel = $this -> wechatPay($uid, $order_id);	
					break;
				case 2://支付宝支付
					//$rel =  $this -> buyVipByAlipay($user_id, $order_id);
					break;
				case 3://现金支付
					//$rel = $this -> xianjinPay($user_id, $order_id);
					$rel['code'] = 200;
					$rel['data'] = '请在30分钟内完成现金付款，否则订单失效！';
					break;
				default:
					return array_out('-9999', '支付类型无效');
					break;
			}

			//更新订单支付方式 
			$map = [];
			$map['id'] = $order_id;
			
			$rel1 = model('UcMemberBalance', 'model\user') -> where($map) -> setField('pay_type', $pay_type);
			
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/
			if($rel['code'] == 200){
				DB::commit();
            	return array_out(200, 'success', $rel['data']);
			}else{
				DB::rollback();
				return array_out($rel['code'], $rel['message'], $rel['data']);
			}
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    	
    }

    /**
     * 微信支付
     * @param int $user_id  用户id
     * @param int $order_id       订单id
     * @return array
     */
    private function wechatPay($user_id, $order_id){
		$rel = model('UcMemberBalance', 'model\user') -> find($order_id);
		if(!$rel) return array_out(-1001, '订单id无效');

		$ordercode = $rel['order_code'];
        //$pay_price = $rel['pay_price'];
        //$pay_price = 0.01;
		if(config('develop_mode') == 1){
			$pay_price = 0.01;
		}else{
			$pay_price = $rel['pay_price'];
		}
		
		//微信支付
		$body = "支付订单号：".$ordercode;
		$rel5 = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> getPrePayOrder($body, $out_trade_no = $ordercode, $total_fee = $pay_price*100, $notify_url = $_SERVER['HTTP_HOST'].url('publics/notify', ['api_token' => 'api_xiangmu']));//dump($notify_url);
		if($rel5['return_code'] != 'SUCCESS') return array_out(-1001, '订单生成失败');

		$data = [];
		$data['appid'] = $rel5['appid'];

		$transferPayment_rel = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> transferPayment($rel5['prepay_id']);
		$transferPayment_rel['payType'] = 0;
		$transferPayment_rel['orderId'] = $order_id;
		Cache::set('order_wechatpay_'.$order_id, $transferPayment_rel, 60*60*24);

		return array_out(200, '生成预付款订单成功', $transferPayment_rel);
	}
	
}